const fs = require('fs');
const path = require('path');

// 生成文件：src/generated/routes-map.js
const viewsDir = path.resolve(__dirname, '..', 'src', 'views');
const outDir = path.resolve(__dirname, '..', 'src', 'generated');
const outFile = path.resolve(outDir, 'routes-map.js');

if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });

const items = fs.readdirSync(viewsDir, { withFileTypes: true })
  .filter(d => d.isDirectory())
  .map(d => d.name)
  .filter(name => fs.existsSync(path.join(viewsDir, name, 'routes.js')));

// Build the content
let content = `// THIS FILE IS AUTO-GENERATED BY scripts/generate-routes-map.js
// Do not edit by hand.

`;

content += `module.exports = function getRoutes() {
  const appName = process.env.VUE_APP_CURRENT_APP;
`;

items.forEach(name => {
  content += `  if (appName === '${name}') { return require('@/views/${name}/routes.js').default; }
`;
});

// default: fallback to first found or empty
if (items.length > 0) {
  content += `  return require('@/views/${items[0]}/routes.js').default;
`;
} else {
  content += `  return [];
`;
}

content += `};
`;

fs.writeFileSync(outFile, content, 'utf8');
console.log('[generate-routes-map] generated', outFile);
